import java.util.*;

class Solution692 {

    public List<String> topKFrequent(String[] words, int k) {
         Map<String , Integer> map = new HashMap<>() ;
         HashSet<String> set = new HashSet<>() ;
         PriorityQueue<String> queue = new PriorityQueue<>(
            (o1,o2)->{
              int flg =  map.get(o1).compareTo(map.get(o2) );
              if(flg == 0){
                return ((String)o2).compareTo((String)o1) ; 
              }
              return flg ; 
            }
         );
         for(String str : words){
            map.put(str , map.getOrDefault(str , 0)+1) ;
            set.add(str) ; 
         }
         for(String str : words){
            if(set.contains(str)){
                if(queue.size() < k){
                queue.offer(str) ;
            }else{
                if(map.get(queue.peek()) < map.get(str)){
                    queue.poll() ;
                    queue.offer(str) ; 
                }else if(map.get(queue.peek()).equals(map.get(str))){
                     if(queue.peek().compareTo(str) > 0){
                        queue.poll() ;
                        queue.offer(str);
                     }
                }
             }
             set.remove(str) ; 
            }
         }
      List<String> list = new ArrayList<>() ;
      while(!queue.isEmpty()){
        list.add(queue.poll());
      }
      Collections.reverse(list) ;
     return list ;
 
    }
}